package com.jiliang.member.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.jiliang.common.result.Errors;
import com.jiliang.common.result.WebResult;
import com.jiliang.member.dto.MemberLoginBo;
import com.jiliang.member.service.MemberLoginService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/memberLogin")
public class MemberLoginController {
    @Resource
    private MemberLoginService memberLoginService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final RandomGenerator randomGenerator = new RandomGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 4);

    /**
     * 获取图形验证码
     * @param response
     * @return
     */
    @GetMapping("/captcha/{uuid}")
    public WebResult<Object> getCaptcha(@PathVariable("uuid")Integer uuid, HttpServletResponse response){
        // 生成验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        captcha.setGenerator(randomGenerator);
        // 将验证码的答案存储到 Redis
        String captchaAnswer = captcha.getCode().toLowerCase();
        // 假设使用 RedisTemplate
        stringRedisTemplate.opsForValue().set("captcha:" + uuid, captchaAnswer, 3, TimeUnit.MINUTES);
        // 将验证码图片写入响应
        response.setContentType("image/png");
        try {
            captcha.write(response.getOutputStream());
            return WebResult.success();
        } catch (IOException e) {
            return WebResult.fail(Errors.SYSTEM_CALL_INTERFACE_ERROR,"验证码生成失败");
        }
    }

    /** 登录接口 */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public WebResult<Object> login(@RequestBody MemberLoginBo bo) {
//        String storedCaptcha = stringRedisTemplate.opsForValue().get("captcha:" + bo.getKeyId());
//        if (storedCaptcha != null && storedCaptcha.equals(bo.getCaptcha().toLowerCase())){
            return WebResult.success(memberLoginService.login(bo.getLoginName(),bo.getLoginPwd()));
//        }else {
//            return WebResult.fail(Errors.VALIDATION_NOT_NULL,"验证码错误");
//        }
    }

    /** Token获取用户信息 */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public WebResult<Object> getInfo(@RequestHeader("Authorization") String authorizationHeader) {
        String token = authorizationHeader.replace("Bearer ", "");
        return WebResult.success(memberLoginService.getUserInfo(token));
    }

    /** 登出接口 */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public WebResult<Object> logout(@RequestHeader("Authorization") String authorizationHeader) {
       return WebResult.success(memberLoginService.logout(authorizationHeader.replace("Bearer ", "")));
    }

    /** 改密接口 */
    @RequestMapping(value = "/alterPass", method = RequestMethod.POST)
    public WebResult<Object> alterPass(@RequestBody @Validated(MemberLoginBo.AlterPass.class) MemberLoginBo bo) {
        return WebResult.success(memberLoginService.alterPassword(bo.getBoId(),bo.getLoginPwd()));
    }

}
